package org.crazyit.cloud;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Random;

/**
 * @Author JLL
 * 定义完这个类之后，要告诉spring容器这个类的存在。
 */
@Slf4j
public class MyRule implements IRule {

    private ILoadBalancer lb;

    public Server choose(Object key) {
        System.out.println("这是自定义规则类");
        Random r = new Random();
        int rNum = r.nextInt(10);
        log.info("lb={}",lb);
        List<Server> servers = lb.getAllServers();
        if(rNum > 7){
            return getServerByPorts(servers,8081);
        }
        return getServerByPorts(servers,8080);
    }

    public Server getServerByPorts(List<Server> servers,int port){
        for (Server s : servers) {
            if(s.getPort() == port){
                return s;
            }
        }
        return null;
    }



    public void setLoadBalancer(ILoadBalancer iLoadBalancer) {

    }

    public ILoadBalancer getLoadBalancer() {
        return null;
    }
}
